#!/bin/bash

INSTALL_DIR := @prefix@
srcdir := $(shell cd @top_srcdir@ && pwd)

MAKE_JOBS := 16

LINUX_DIR := $(srcdir)/linux-headers/

CFLAGS += -Wno-error
# Check that we have gawk installed.  Set awk=gawk if necessary.
SHELL := /bin/sh
ifeq ($(shell awk --version | grep GNU),)
ifeq ($(shell gawk --version),)
$(error You must have gawk installed on your system!)
else
SHELL := PATH="$(srcdir)/scripts:$(PATH)" $(SHELL)
endif
endif

newlib: build-gcc-newlib

build-binutils-newlib: binutils
	rm -rf $@ $(notdir $@)
	mkdir $(notdir $@)
	cd $@ && \
	$(shell pwd)/$</configure \
		--target=riscv-elf \
		--prefix=$(INSTALL_DIR) \
		--enable-tls \
        CFLAGS="-g -O2 -Wno-error"

	$(MAKE) -C $@ -j $(MAKE_JOBS)
	$(MAKE) -C $@ -j $(MAKE_JOBS) install

newlib-gcc: gcc newlib
	rm -rf $@
	cp -r $(shell pwd)/gcc $@
	cp -r $(shell pwd)/newlib/newlib $@
	cp -r $(shell pwd)/newlib/libgloss $@

build-gcc-newlib: newlib-gcc build-binutils-newlib
	rm -rf $@ $(notdir $@)
	mkdir $(notdir $@)
	cd $@ && $(shell pwd)/$</configure \
		--target=riscv-elf \
		--prefix=$(INSTALL_DIR) \
		--disable-shared \
		--disable-threads \
		--enable-tls \
		--enable-languages=c,c++ \
		--with-newlib \
		--disable-libmudflap \
		--disable-libssp \
		--disable-libquadmath \
		--disable-libgomp \
		--disable-nls
	$(MAKE) -C $@ -j $(MAKE_JOBS) inhibit-libc=true
	$(MAKE) -C $@ -j $(MAKE_JOBS) install
	for i in $(INSTALL_DIR)/bin/riscv-elf-*; do j=`echo $$i | sed 's/riscv-elf-/riscv-/'`; if [ ! -f $$j ]; then ln -s `basename $$i` $$j; fi; done

clean:
	rm -rf build-* newlib-gcc

distclean:
	rm -rf build-* newlib-gcc

# All of the packages install themselves, so our install target does nothing.
install:
